package com.hyjiacan.tools.apps.dbm.utils

public object Sql {
    /**
     * 解析SQL中的SQL语句
     */
    public fun count(sql: String): Int {
        var meetQuoteS = false
        var meetQuoteD = false
        var meetSlash = false

        var c = 0

        var prevCh: Char? = null

        sql.iterator().forEach { ch ->
            prevCh = ch
            if (meetSlash) {
                meetSlash = false
                return@forEach
            }

            when (ch) {
                '\\' -> {
                    meetSlash = true
                    return@forEach
                }

                ';' -> {
                    if (meetQuoteD || meetQuoteS) {
                        meetSlash = false
                    } else {
                        c += 1
                    }
                    return@forEach
                }

                '\'' -> {
                    if (meetQuoteS) {
                        meetQuoteS = false
                        return@forEach
                    }
                    if (meetQuoteD) {
                        return@forEach
                    }
                    meetQuoteS = true
                    return@forEach
                }

                '"' -> {
                    if (meetQuoteD) {
                        meetQuoteD = false
                        return@forEach
                    }
                    if (meetQuoteS) {
                        return@forEach
                    }
                    meetQuoteD = true
                    return@forEach
                }
            }
        }

        if (prevCh != null && prevCh != ';') {
            c += 1
        }
        return c
    }
}